<?php

class RoleController extends Controller
{
   /**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
	public function actionIndex()
	{ 
		Yii::app()->session['session_user'] = md5(time());  
	   $model = new Role();
      
      $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 1; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'ASC'; // Lấy giá trị muốn sắp xếp
      $rowList = array(10,20,30,50,100);  
      $total_record = $model->count();
      if(!is_numeric($page)) $page = 1;
      if(!is_numeric($limit)) $limit = 10;
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
       
      if ($page > $total_pages) $page=$total_pages;
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy\
      if(isset($_POST['Role'])){
         $params = array_diff($_POST['Role'],array(0)); // Xóa những phần tử bằng 0
         $model->attributes = $params;
         $list = $model->getAll('',$params);
      }else{
         $list = $model->getAll($start.','.$limit);   
      }
      
		//List group member
      $memberGroup = new Membergroup();
      $object = $memberGroup->findAll("IsActive =:IsActive",array("IsActive" => 1));
      $groupList = array(0 => '-- Chọn nhóm --');
      if(count($object) > 0){
         foreach($object as $item){
            $groupList[$item['MemberGroupID']] = $item['MembergroupName'];
         }
      }
      
      //Menu tree
      $menuadmin = new Menuadmin();
      $all_menu = $menuadmin->getAll();
      $tree_menu = $menuadmin->getTree($all_menu);
      //CVarDumper::dump($tree_menu,10,true);die();
      $this->render('index',array("model" => $model,
                                  "list" => $list,
                                  "session_user" => Yii::app()->session['session_user'],
                                  "groupList" => $groupList,
                                  "menu_tree" => $tree_menu,
                                  "list" => $list,
                                  "rowList" => $rowList,
                                  "page" => $page,
                                  "start" => $start,
                                  "limit" => $limit,
                                  "sidx" => $sidx,
                                  "sord" => $sord,
                                  "total_record" => $total_record,
                                  "total_pages" => $total_pages,
                                  ));
	}
   
   /**
    * Create role
   */
   public function actionCreate(){
      $model = new Role();
      //Check login
      if(!Member::checkLogged()){
         $this->redirect('/site/login');
      }else{
         $message = '';
         $memberGroup = new Membergroup();
         $object = $memberGroup->findAll("IsActive =:IsActive",array("IsActive" => 1));
         $groupList = array();
         if(count($object) > 0){
            foreach($object as $item){
               $groupList[$item['MemberGroupID']] = $item['MembergroupName'];
            }
         }
         $menuadmin = new Menuadmin();
         $all_menu = $menuadmin->getAll();
         $tree_menu = $menuadmin->getTree($all_menu);
         if(isset($_POST['Role'])){
            $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
            $session_user = Yii::app()->request->getParam('session_user');
            
            if(Yii::app()->session['session_user'] == $session_user){
               $model->attributes = $_POST['Role'];
               if($model->validate()){
                  $model->save();
                  $message = 'Thêm mới thành công';
                  if($action_user == 'save')
                     $this->redirect('/index.php/admin/'.$this->id);
               }   
            }
            
         }
      }
      $this->layout = '//layouts/cms/create';
      $this->render('create',array('model' => $model,
                                    'groupList' => $groupList,
                                    'menu_tree' => $tree_menu,
                                    'message' => $message,
                                    'session_user' =>  Yii::app()->session['session_user'],
                                    ));
      
   }
   
   /**
    * Edit role
   */
   public function actionEdit(){
      $model = new Role();
      $message = '';
      //Check login
      if(!Member::checkLogged())
         $this->redirect('/site/login');
      else{
         
         //List group member
         $memberGroup = new Membergroup();
         $object = $memberGroup->findAll("IsActive =:IsActive",array("IsActive" => 1));
         $groupList = array();
         if(count($object) > 0){
            foreach($object as $item){
               $groupList[$item['MemberGroupID']] = $item['MembergroupName'];
            }
         }
         
         //Menu tree
         $menuadmin = new Menuadmin();
         $menu_level_1 = $menuadmin->getAllLevel1();
         $menu_tree = array();
         
         if(count($menu_level_1) > 0){
            foreach($menu_level_1 as $item){
               $menu_tree[$item['MenuAdminID']] = $item['MenuName'];
               
               //Get menu level 2
               $menu_level = $menuadmin->getChild($item['MenuAdminID']);
               if(isset($menu_level[2]) && count($menu_level[2]) > 0){
                  foreach($menu_level[2] as $item_2){
                     $menu_tree[$item_2['MenuAdminID']] = "|--- " . $item_2['MenuName'];
                  }
               }
               
            }
         }
         
         $id = Yii::app()->request->getParam('id',0);
         $model = Role::model()->findByPk($id);
         if(isset($_POST['Role'])){
            $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
            $session_user = Yii::app()->request->getParam('session_user');
            if($session_user == Yii::app()->session['session_user']){
               $model->attributes = $_POST['Role'];
               if($model->validate()){
                  $model->save();
                  $message = "Cập nhật thành công";
               }
               if($action_user == 'save')
                  $this->redirect('/index.php/admin/'.$this->id);
            }
            
         }
         
      }
      $this->layout = '//layouts/cms/create';
      $this->render('edit',array('model' => $model,
                                 'groupList' => $groupList,
                                 'menu_tree' => $menu_tree,
                                 'message' => $message,
                                 'session_user' => Yii::app()->session['session_user'],
                                 ));
   }
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM role WHERE RoleID IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
  
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}